import { defineStore } from "pinia";
import { ref } from "vue";

export interface Tab {
  name: string; // 路由path
  title: string;
}

export const useTabsStore = defineStore("tabs", () => {
  const tabs = ref<Tab[]>([{ name: "/", title: "首页" }]);
  const activeTab = ref("/");

  function addTab(tab: Tab) {
    if (!tabs.value.find((t) => t.name === tab.name)) {
      tabs.value.push(tab);
    }
    activeTab.value = tab.name;
  }

  function removeTab(name: string) {
    const idx = tabs.value.findIndex((t) => t.name === name);
    if (idx !== -1) {
      tabs.value.splice(idx, 1);
      if (activeTab.value === name) {
        const nextTab = tabs.value[idx] || tabs.value[idx - 1] || tabs.value[0];
        if (nextTab) activeTab.value = nextTab.name;
      }
    }
  }

  function setActiveTab(name: string) {
    activeTab.value = name;
  }

  return { tabs, activeTab, addTab, removeTab, setActiveTab };
});
